#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

#define BMP_Header_Length 54 
/**
 * save scene to bmp file
 * @param: string out filename : the filename of the output file
 * @return: 
 */
void saveBmp(string outfilename) 
{ 
	FILE* pDummyFile; 
	FILE* pWritingFile; 
	GLubyte* pPixelData; 
	GLubyte BMP_Header[BMP_Header_Length]; 
	GLint i, j; 
	GLint PixelDataLength; 

	// calculate the length 
	i = WindowWidth * 3;
	while( i%4 != 0 ) 
		++i;  
	PixelDataLength = i * WindowHeight; 
 
	pPixelData = (GLubyte*)malloc(PixelDataLength); 
	if( pPixelData == 0 ) 
		exit(0); 

	pDummyFile = fopen("dummy.bmp", "rb"); 
	if( pDummyFile == 0 ) 
		exit(0); 

	pWritingFile = fopen(outfilename.data(), "wb"); 
	if( pWritingFile == 0 ) 
		exit(0); 

	// read pixel of the scene
	glPixelStorei(GL_UNPACK_ALIGNMENT, 4); 
	glReadPixels(0, 0, WindowWidth, WindowHeight, 
		GL_BGR_EXT, GL_UNSIGNED_BYTE, pPixelData); 

	// copy the file header of dummy.bmp to the new file 
	fread(BMP_Header, sizeof(BMP_Header), 1, pDummyFile); 
	fwrite(BMP_Header, sizeof(BMP_Header), 1, pWritingFile); 
	fseek(pWritingFile, 0x0012, SEEK_SET); 
	i = WindowWidth; 
	j = WindowHeight; 
	fwrite(&i, sizeof(i), 1, pWritingFile); 
	fwrite(&j, sizeof(j), 1, pWritingFile); 

	// write the file
	fseek(pWritingFile, 0, SEEK_END); 
	fwrite(pPixelData, PixelDataLength, 1, pWritingFile); 

	// release 
	fclose(pDummyFile); 
	fclose(pWritingFile); 
	free(pPixelData); 
}
